import readPkgUp from "read-pkg-up";
import semver from "semver";
import inquirer from "inquirer";

const RELEASE_TYPES: semver.ReleaseType[] = [
  "patch",
  "minor",
  "major",
  "prepatch",
  "preminor",
  "premajor",
  "prerelease",
];
const PRERELEASE_VERSIONS = ["prepatch", "preminor", "premajor", "prerelease"];

const getPkg = () => {
  const { pkg } = readPkgUp.sync();

  if (!pkg) {
    throw new Error(
      `No package.json found. Make sure you're in the correct project.`,
    );
  }

  return pkg;
};

const getNewVersion = (
  version: string,
  release: semver.ReleaseType = "prerelease",
  preId: string = "",
) => {
  return semver.inc(version, release, true, preId);
};

const { version } = getPkg();

(async () => {
  const answer: any = await inquirer.prompt([
    {
      type: "list",
      name: "type",
      message: `Select a new version (currently ${version}) (Use arrow keys)`,
      choices: RELEASE_TYPES.map((type, index) => {
        const newVersion = getNewVersion(version, type);
        const isCustom = type === "prerelease";
        if (isCustom) return { name: type };
        return {
          name: `${type} (${newVersion})`,
        };
      }),
    },
  ]);

  let newVersion = getNewVersion(version, answer.type);

  if (answer.type === "prerelease") {
    const { tag }: any = await inquirer.prompt({
      type: "input",
      name: "tag",
      message: `Enter a prerelease identifier (default: none, yielding ${newVersion})`,
      filter: function(tag: string) {
        return getNewVersion(version, answer.type, tag) || "";
      },
    });
    newVersion = tag;
  }
  console.log(version, "->", newVersion);
})();
